from flask import Blueprint, request, current_app
from flask_jwt_extended import jwt_required, current_user
from backend.models import db, Footprint, Property, User
from backend.utils import api_response, format_response
# 假设您有一个admin_required装饰器，类似properties.py
from backend.decorators import admin_required

footprints_bp = Blueprint('footprints', __name__)


@footprints_bp.route('', methods=['GET'])
@jwt_required()
@format_response
def get_footprints():
    """
    获取足迹。
    管理员获取所有用户的足迹，普通用户仅获取自己的足迹。支持分页。
    """
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)

    query = Footprint.query

    if current_user.role != 'admin':
        query = query.filter_by(user_id=current_user.id)

    # 按添加时间降序排序，最新的在前
    query = query.order_by(Footprint.added_at.desc())

    pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    # 序列化足迹数据，为管理员界面补充用户信息
    def serialize_footprint_for_admin(fp):
        data = fp.to_dict()
        data['user_id'] = fp.user_id
        data['property_id'] = fp.property_id
        data['username'] = fp.user.username if fp.user else '未知用户'
        return data

    return {
        "list": [serialize_footprint_for_admin(fp) for fp in pagination.items],
        "pagination": {
            "current_page": pagination.page,
            "per_page": pagination.per_page,
            "total_items": pagination.total,
            "total_pages": pagination.pages
        }
    }, 200


@footprints_bp.route('/<int:property_id>', methods=['POST'])
@jwt_required()
@format_response
def add_footprint(property_id):
    """将一个小区添加到用户的足迹"""
    if not Property.query.get(property_id):
        return api_response(code=404, message="小区不存在")
    if Footprint.query.get((current_user.id, property_id)):
        return api_response(code=409, message="该小区已在您的足迹中")
    data = request.json or {}
    new_footprint = Footprint(user_id=current_user.id, property_id=property_id, notes=data.get('notes'),
                              rating=data.get('rating'))
    db.session.add(new_footprint)
    db.session.commit()
    return new_footprint.to_dict(), 201


@footprints_bp.route('/<int:property_id>', methods=['PUT'])
@jwt_required()
@format_response
def update_footprint(property_id):
    """
    更新足迹的笔记或评级。
    管理员可以通过在请求体中传递 user_id 来更新指定用户的足迹。
    """
    data = request.json
    user_id_to_update = current_user.id

    # 如果当前用户是管理员，并且请求中指定了user_id，则允许编辑该用户的足迹
    if current_user.role == 'admin' and 'user_id' in data:
        user_id_to_update = data.get('user_id')

    footprint = Footprint.query.get_or_404((user_id_to_update, property_id))

    if 'notes' in data:
        footprint.notes = data['notes']
    if 'rating' in data:
        footprint.rating = data['rating']

    db.session.commit()
    return footprint.to_dict(), 200


@footprints_bp.route('/batch-clear-notes', methods=['PUT'])
@jwt_required()
@admin_required
@format_response
def batch_clear_notes():

    data = request.get_json()
    if not data or 'footprints' not in data or not isinstance(data['footprints'], list):
        return api_response(code=400, message="请求体格式错误, 需要包含 'footprints' 列表。")

    # 从请求中提取复合主键
    footprint_keys = [
        (item.get('user_id'), item.get('property_id'))
        for item in data['footprints'] if item.get('user_id') and item.get('property_id')
    ]

    if not footprint_keys:
        return api_response(code=400, message="请求的 'footprints' 列表为空或格式不正确。")

    # 使用 tuple_ 高效查询
    footprints_to_update = Footprint.query.filter(
        db.tuple_(Footprint.user_id, Footprint.property_id).in_(footprint_keys)
    ).all()

    if not footprints_to_update:
        return api_response(code=404, message="未找到任何匹配的足迹记录。")

    updated_count = 0
    for fp in footprints_to_update:
        if fp.notes is not None and fp.notes != '':
            fp.notes = ''  # 清空评价
            updated_count += 1

    if updated_count > 0:
        db.session.commit()

    return {"message": f"成功清空了 {updated_count} 条记录的评价。"}, 200


@footprints_bp.route('/<int:user_id>/<int:property_id>', methods=['DELETE'])
@jwt_required()
@admin_required
@format_response
def admin_delete_footprint(user_id, property_id):
    """[仅管理员] 删除指定用户的指定足迹记录"""
    footprint = Footprint.query.get_or_404((user_id, property_id))
    db.session.delete(footprint)
    db.session.commit()
    return {"message": "足迹已成功删除"}, 200


@footprints_bp.route('/<int:property_id>', methods=['DELETE'])
@jwt_required()
@format_response
def delete_footprint(property_id):
    """从足迹中移除一个小区"""
    footprint = Footprint.query.get_or_404((current_user.id, property_id))
    db.session.delete(footprint)
    db.session.commit()
    return {"message": "足迹已成功移除"}, 200